<?php


namespace App\Http\Controllers\Web;

use App\Models\CashApply;
use App\Models\CreditLog;
use App\Models\RechargeLog;
use App\Services\CashApplyService;
use App\Services\OfficialTemplateService;
use App\Services\WechatService;
use App\User;

/**
 * 余额
 * Class BalanceController
 * @package App\Http\Controllers\Web
 */
class BalanceController extends Controller
{
    /**
     * 提现记录
     */
    public function rechargeRecord()
    {
        $query = $this->query;

        $keywords = trim($query['keywords']);
        $startTime = $query['start_time'];
        $endTime = $query['end_time'];

        unset($query['start_time'], $query['end_time'], $query['keywords']);
        $builder = RechargeLog::with('user');

        if($keywords){
            $userIds = User::where(function ($query) use ($keywords) {
                $query->where('nickname', 'like', "%{$keywords}%");
                $query->orWhere('mobile', 'like', "%{$keywords}%");

            })->get()->pluck('id')->toArray();
            if ($userIds) {
                $builder->whereIn('uid', $userIds);
            } else {
                $builder->where('uid', 0);
            }
        }
        if ($startTime) {
            $builder->where('created_at', '>=', strtotime($startTime));
        }
        if ($endTime) {
            $builder->where('created_at', '<=', strtotime($endTime));
        }
        $builder->orderBy('id', 'desc');
        $pager = $builder->paginate($this->pageNum);
        return view('balance.recharge_record', [
            'pager' => $pager,
        ]);
    }

    /**
     * 余额明细列表
     */
    public function detail()
    {
        //获取分页数据
        $query = $this->query;

        $queryData['log_type'] = CreditLog::$logType;

        $keywords = trim($query['keywords']);
        $startTime = $query['start_time'];
        $endTime = $query['end_time'];

        $builder = CreditLog::with('user');

        if($query['log_type']){
            $builder->whereLogType($query['log_type']);
        }
        if ($keywords) {
            $userIds = User::where(function ($query) use ($keywords) {
                $query->orWhere('nickname', 'like', "%{$keywords}%");
                $query->orWhere('realname', 'like', "%{$keywords}%");
                $query->orWhere('mobile', 'like', "%{$keywords}%");
            })->get()->pluck('id')->toArray();
            if ($userIds) {
                $builder->whereIn('uid', $userIds);
            } else {
                $builder->where('uid', 0);
            }
        }

        if ($startTime) {
            $builder->where('created_at', '>=', strtotime($startTime));
        }
        if ($endTime) {
            $builder->where('created_at', '<=', strtotime($endTime));
        }

        $builder->orderBy('id', 'desc');

        $pager = $builder->paginate($this->pageNum);

        return view('balance.detail', [
            'pager' => $pager,
            'queryData' => $queryData,
        ]);
    }

    /**
     * 提现申请
     */
    public function withdrawApply()
    {
        //获取分页数据
        $query = $this->query;

        $queryData['type'] = CashApply::$typeEnum;
        $queryData['status'] = CashApply::$statusEnum;
        $queryData['pay_type'] = CashApply::$payTypeEnum;

        $keywords = trim($query['keywords']);
        $startTime = $query['start_time'];
        $endTime = $query['end_time'];

        unset($query['start_time'], $query['end_time'], $query['keywords']);

        $builder = CashApply::whereCashType('yue')->whereCategory(2)->with('user');
        if($query['type']){
            $builder->whereType($query['type']);
        }
        if($query['status']){
            $builder->whereStatus($query['status']);
        }
        if($query['pay_type']){
            $builder->wherePayType($query['pay_type']);
        }

        if ($keywords) {
            $userIds = User::where(function ($query) use ($keywords) {
                $query->orWhere('nickname', 'like', "%{$keywords}%");
                $query->orWhere('realname', 'like', "%{$keywords}%");
                $query->orWhere('mobile', 'like', "%{$keywords}%");
            })->get()->pluck('id')->toArray();
            if ($userIds) {
                $builder->whereIn('uid', $userIds);
            } else {
                $builder->where('uid', 0);
            }
        }

        if ($startTime) {
            $builder->where('created_at', '>=', strtotime($startTime));
        }
        if ($endTime) {
            $builder->where('created_at', '<=', strtotime($endTime));
        }

        $builder->orderBy('id', 'desc');

        $pager = $builder->paginate($this->pageNum);

        return view('balance.withdraw_apply', [
            'pager' => $pager,
            'queryData' => $queryData,
        ]);
    }

    /**
     * 提现申请审核
     * @throws \Throwable
     */
    public function withdrawApplyCheck()
    {
        $id = request()->input('id');
        $status = (int)request()->input('status');
        $payType = (int)request()->input('pay_type');
        $failMsg = trim(request()->input('fail_msg'));

        $model = CashApply::with('user')->find($id);
        if($model->status == 1){
            return  $this->error(-1,'已处理，请不要重复提交');
        }
        $model->status = $status;

        if ($status == -1) {
            //驳回
            $ret = CashApplyService::balanceCheckFail($model, $failMsg);
            return $this->success();
        }

        //审核通过
        if ($status == 1) {
            $model->pay_type = $payType;
            $model->status = 1;
            if ($payType == 1) {
                $model->save();
                $ret = CashApplyService::balanceCheckSuccess($model);
                return $this->success();
            } else {
                //线上打款
                $app = WechatService::payment();
                $data = [
                    'partner_trade_no' => CashApplyService::createOrderNo(),
                    'openid' => $model->user->wxapp_openid,
                    'check_name' => 'FORCE_CHECK',
                    're_user_name' => $model->real_name,//$model->user->realname,
                    'amount' => ($model->balance - $model->commission) * 100,
                    'desc' => '余额提现',
                ];
                $res = $app->transfer->toBalance($data);
                if ($res['result_code'] != 'FAIL') {
                    $model->save();
                    CashApplyService::balanceCheckSuccess($model);
                    return $this->success();
                } else {
                    $model->status = -2;
                    $model->fail_msg = $res['err_code_des'];
                    $model->fail_time = time();
                    $model->save();
                    OfficialTemplateService::sendWithdrawFail($model);
                    return $this->error(-1, '打款失败:' . $res['err_code_des']);
                }
            }
        }

        return $this->error(-1, '系统错误');
    }


}
